import axios, { AxiosRequestConfig } from "axios";
import { getToken, setToken, getItem } from "@/utils/storage";
import { baseMsg, formatTime } from "@/utils/utils";
import store from "@/store";
const baseURL = process.env.VUE_APP_BASE_API


const request = axios.create({
  baseURL: baseURL,
  timeout: 100000000,
});

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    const token = getToken();
    config.headers["X-Request-Plat"] = "Web";
    config.headers["X-Request-Timestamp"] = formatTime(new Date());
    if (token) {
      config.headers["X-Request-Token"] = token;
    }
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    const res = response.data;

    // 如果Code码为0，则进行错误统一处理
    if (res.code !== 4201 && res.code !== 4202) {
      baseMsg(res.msg, false);
      if (res.code >= 4301 && res.code <= 4399 && getToken()) {
        store.dispatch("user/FedLogOut");
      }
    } else {
      return response;
    }
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

// request 不支持泛型
// request.get / post/ put 支持相应数据泛型
// 由于后端包装一层数据 data ，导致访问数据比较麻烦，所以封装了 request
export default <T = any>(config: AxiosRequestConfig) => {
  return request(config).then((res) => (res.data || res) as T);
};
